<template>
  <div>
    <el-container>
      <SidebarMenu
        :default-active="activeMenu"
        @goToRoleManagement="goToRoleManagement"
        @goToMenuManagement="goToMenuManagement"
        @goToPermissionControl="goToPermissionControl"
        @goToSystemSetting="goToSystemSetting"
        @goToLogManagement="goToLogManagement"
        @goToFileManagement="goToFileManagement"
        @goToArticleManagement="goToArticleManagement"
        @goToUserInfoManagement="goToUserInfoManagement"
      />

      <el-container>
        <el-header>
          <Navbar title="用户信息管理" :avatar="currentAvatar" />
        </el-header>

        <el-main>
          <!-- 用户信息卡片 -->
          <el-card class="user-info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span>个人信息</span>
                <div class="header-buttons">
                  <div v-if="!editMode">
                    <el-button type="primary" @click="startEdit">
                      <el-icon><Edit /></el-icon>
                      编辑信息
                    </el-button>
                    <el-button type="danger" @click="handleLogout" class="logout-btn">
                      <el-icon><Close /></el-icon>
                      退出登录
                    </el-button>
                  </div>
                  <div v-else>
                    <el-button type="success" @click="saveUserInfo" :loading="saving">
                      <el-icon><Check /></el-icon>
                      保存
                    </el-button>
                    <el-button @click="cancelEdit">
                      <el-icon><Close /></el-icon>
                      取消
                    </el-button>
                  </div>
                </div>
              </div>
            </template>

            <el-form 
              :model="userForm" 
              :rules="formRules" 
              ref="userFormRef" 
              label-width="120px"
              :disabled="!editMode"
            >
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="昵称" prop="nickname">
                    <el-input 
                      v-model="userForm.nickname" 
                      placeholder="请输入昵称"
                      :maxlength="50"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="邮箱" prop="email">
                    <el-input 
                      v-model="userForm.email" 
                      placeholder="请输入邮箱"
                      :maxlength="100"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phone">
                    <el-input 
                      v-model="userForm.phone" 
                      placeholder="请输入手机号"
                      :maxlength="20"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="头像" prop="avatar">
                    <el-input 
                      v-model="userForm.avatar" 
                      placeholder="请输入头像URL"
                      :maxlength="500"
                      show-word-limit
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态">
                    <el-tag :type="userForm.status === 1 ? 'success' : 'danger'">
                      {{ userForm.status === 1 ? '正常' : '禁用' }}
                    </el-tag>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="创建时间">
                    <el-input :value="formatDate(userForm.createdAt)" disabled />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="更新时间">
                    <el-input :value="formatDate(userForm.updatedAt)" disabled />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>

          <!-- 角色信息卡片 -->
          <el-card class="role-info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span>角色信息</span>
              </div>
            </template>

            <el-table :data="userRoles" style="width: 100%">
              <el-table-column prop="roleName" label="角色名称" />
              <el-table-column prop="roleDescription" label="角色描述" />
              <el-table-column prop="createdAt" label="分配时间">
                <template #default="scope">
                  {{ formatDate(scope.row.createdAt) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>

          <!-- 权限信息卡片 -->
          <el-card class="permission-info-card" shadow="never">
            <template #header>
              <div class="card-header">
                <span>权限信息</span>
              </div>
            </template>

            <div class="permission-tags">
              <el-tag 
                v-for="permission in userPermissions" 
                :key="permission"
                type="info"
                class="permission-tag"
              >
                {{ permission }}
              </el-tag>
              <el-empty v-if="userPermissions.length === 0" description="暂无权限信息" />
            </div>
          </el-card>

          <!-- 底部操作区域 -->
          <div class="bottom-actions">
            <el-button type="danger" size="large" @click="handleLogout" class="logout-btn-large">
              <el-icon><Close /></el-icon>
              退出登录
            </el-button>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Edit, Check, Close } from '@element-plus/icons-vue';
import SidebarMenu from './SidebarMenu.vue';
import Navbar from './CommonNavbar.vue';
import api from '../utils/request.js';
import { useAuthStore } from '@/stores/auth';

const router = useRouter();

// 响应式数据
const editMode = ref(false);
const saving = ref(false);
const userFormRef = ref();
const currentAvatar = ref('https://i.gtimg.cn/club/item/face/img/2/15922_100.gif');
const activeMenu = ref('UserInfoManagement');

// 用户表单数据
const userForm = reactive({
  id: '',
  username: '',
  nickname: '',
  email: '',
  phone: '',
  avatar: '',
  status: 1,
  createdAt: null,
  updatedAt: null
});

// 用户角色和权限
const userRoles = ref([]);
const userPermissions = ref([]);

// 表单验证规则
const formRules = {
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    { max: 100, message: '邮箱长度不能超过100个字符', trigger: 'blur' }
  ],
  phone: [
    { max: 20, message: '手机号长度不能超过20个字符', trigger: 'blur' },
    { pattern: /^[0-9+\-\s()]*$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  avatar: [
    { max: 500, message: '头像URL长度不能超过500个字符', trigger: 'blur' }
  ]
};

// 开始编辑
const startEdit = () => {
  editMode.value = true;
  // 聚焦到第一个可编辑字段
  setTimeout(() => {
    const nicknameInput = document.querySelector('input[placeholder="请输入昵称"]');
    if (nicknameInput) {
      nicknameInput.focus();
    }
  }, 100);
};

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    // 从认证状态获取当前用户信息
    const authStore = useAuthStore();
    const currentUser = authStore.user;
    
    if (!currentUser || !currentUser.userId) {
      ElMessage.error('用户未登录或登录信息无效');
      router.push('/login');
      return;
    }
    
    // 检查是否已经有完整的用户信息（包含email、phone等字段）
    if (currentUser.email && currentUser.phone !== undefined) {
      // 使用已存储的完整用户信息
      Object.assign(userForm, {
        id: currentUser.userId || currentUser.id,
        username: currentUser.username,
        nickname: currentUser.nickname || '',
        email: currentUser.email,
        phone: currentUser.phone || '',
        avatar: currentUser.avatar || '',
        status: currentUser.status,
        createdAt: currentUser.createdAt,
        updatedAt: currentUser.updatedAt
      });

      // 更新角色信息
      userRoles.value = currentUser.roles || [];
      
      // 更新权限信息
      userPermissions.value = currentUser.permissions || [];
      
      // 更新头像
      if (currentUser.avatar) {
        currentAvatar.value = currentUser.avatar;
      }
      
      return; // 重要：如果使用缓存数据，直接返回，不要继续执行API调用
    }
    
    // 如果没有完整信息，则从API获取
    const userId = currentUser.userId;
    const response = await api.get(`/api/user/profile/${userId}`);
    
    if (response.data.success) {
      const userData = response.data.data;
      
      // 更新表单数据
      Object.assign(userForm, {
        id: userData.id,
        username: userData.username,
        nickname: userData.nickname || '',
        email: userData.email,
        phone: userData.phone || '',
        avatar: userData.avatar || '',
        status: userData.status,
        createdAt: userData.createdAt,
        updatedAt: userData.updatedAt
      });

      // 更新角色信息
      userRoles.value = userData.roles || [];
      
      // 更新权限信息
      userPermissions.value = userData.permissions || [];
      
      // 更新头像
      if (userData.avatar) {
        currentAvatar.value = userData.avatar;
      }
      
      // 更新认证状态中的用户信息
      authStore.setUser({
        ...currentUser,
        ...userData
      });
      
      ElMessage.success('获取用户信息成功');
    } else {
      ElMessage.error(response.data.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
      router.push('/login');
    } else {
      ElMessage.error('获取用户信息失败，请检查网络连接');
    }
  }
};

// 保存用户信息
const saveUserInfo = async () => {
  try {
    // 表单验证
    await userFormRef.value.validate();
    
    saving.value = true;
    
    const updateData = {
      userId: userForm.id,
      nickname: userForm.nickname,
      email: userForm.email,
      phone: userForm.phone,
      avatar: userForm.avatar
    };
    
    console.log('发送更新请求:', updateData);
    
    const response = await api.put('/api/user/profile', updateData);
    
    if (response.data.success) {
      ElMessage.success('用户信息保存成功！');
      editMode.value = false;
      
      // 更新认证状态中的用户信息
      const authStore = useAuthStore();
      const currentUser = authStore.user;
      if (currentUser) {
        authStore.updateUserInfo({
          nickname: userForm.nickname,
          email: userForm.email,
          phone: userForm.phone,
          avatar: userForm.avatar,
          updatedAt: new Date().toISOString()
        });
      }
      
      // 重新获取最新的用户信息
      await fetchUserInfo();
    } else {
      ElMessage.error(response.data.message || '保存失败');
    }
  } catch (error) {
    console.error('保存用户信息失败:', error);
    
    // 处理不同类型的错误
    if (error.response?.status === 400) {
      // 业务逻辑错误
      const errorData = error.response.data;
      if (errorData.errors && Array.isArray(errorData.errors)) {
        // 显示具体的验证错误
        errorData.errors.forEach(err => {
          ElMessage.error(err);
        });
      } else {
        ElMessage.error(errorData.message || '输入信息有误，请检查后重试');
      }
    } else if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
      router.push('/login');
    } else if (error.response?.status === 403) {
      ElMessage.error('没有权限修改用户信息');
    } else if (error.response?.status === 404) {
      ElMessage.error('用户不存在');
    } else if (error.response?.status >= 500) {
      ElMessage.error('服务器错误，请稍后重试');
    } else {
      ElMessage.error('保存失败，请检查网络连接');
    }
  } finally {
    saving.value = false;
  }
};

// 取消编辑
const cancelEdit = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的修改将丢失。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '继续编辑',
      type: 'warning',
    }
  ).then(() => {
    editMode.value = false;
    // 重新获取用户信息，恢复原始数据
    fetchUserInfo();
    ElMessage.info('已取消编辑');
  }).catch(() => {
    // 用户选择继续编辑，不做任何操作
  });
};

// 退出登录
const handleLogout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗？退出后将返回登录页面。',
    '退出登录',
    {
      confirmButtonText: '确定退出',
      cancelButtonText: '取消',
      type: 'warning',
      confirmButtonClass: 'el-button--danger',
    }
  ).then(async () => {
    try {
      // 获取当前用户信息用于登出API调用
      const authStore = useAuthStore();
      const currentUser = authStore.user;
      
      if (currentUser && currentUser.userId) {
        // 调用后端登出API（可选）
        try {
          await api.post('/api/auth/logout', {
            token: authStore.token,
            userId: currentUser.userId,
            reason: '用户主动退出登录'
          });
        } catch (error) {
          console.warn('登出API调用失败，继续执行本地登出:', error);
        }
      }
      
      // 清除本地登录状态
      authStore.forceLogout();
      
      ElMessage.success('已成功退出登录');
      
      // 跳转到登录页面
      router.push('/login');
    } catch (error) {
      console.error('退出登录失败:', error);
      ElMessage.error('退出登录失败，请重试');
    }
  }).catch(() => {
    // 用户取消退出
    ElMessage.info('已取消退出登录');
  });
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN');
};

// 导航方法
const goToRoleManagement = () => router.push('/RoleManagement');
const goToMenuManagement = () => router.push('/MenuManagement');
const goToPermissionControl = () => router.push('/PermissionControl');
const goToSystemSetting = () => router.push('/system');
const goToLogManagement = () => router.push('/LogManagement');
const goToFileManagement = () => router.push('/FileManagement');
const goToArticleManagement = () => router.push('/ArticleManagement');
const goToUserInfoManagement = () => router.push('/UserInfoManagement');

// 认证状态检查
const checkAuthStatus = () => {
  const authStore = useAuthStore();
  if (!authStore.token || !authStore.user) {
    ElMessage.error('请先登录');
    router.push('/login');
    return false;
  }
  return true;
};

// 组件挂载时检查认证状态并获取用户信息
onMounted(() => {
  if (checkAuthStatus()) {
    fetchUserInfo();
  }
});
</script>

<style scoped>
.user-info-card,
.role-info-card,
.permission-info-card {
  margin-bottom: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.card-header span {
  font-size: 16px;
}

.header-buttons {
  display: flex;
  gap: 10px;
  align-items: center;
}

.logout-btn {
  margin-left: 10px;
}

.el-form-item {
  margin-bottom: 20px;
}

.permission-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.permission-tag {
  margin: 4px;
}

.el-tag {
  border-radius: 4px;
}

.el-button {
  border-radius: 6px;
}

.el-input {
  border-radius: 4px;
}

.el-select {
  width: 100%;
}

.el-table {
  border-radius: 4px;
}

/* 编辑模式下的样式 */
.el-form.is-disabled .el-input__inner {
  background-color: #f5f7fa;
  color: #606266;
}

/* 底部操作区域 */
.bottom-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.logout-btn-large {
  min-width: 120px;
  height: 40px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-col {
    margin-bottom: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .header-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .logout-btn {
    margin-left: 0;
    margin-top: 10px;
  }
  
  .bottom-actions {
    margin-top: 20px;
    padding: 15px;
  }
}
</style>
